//
//  ShouYeLunBo.m
//  MIDI
//
//  Created by E.M.Game on 15/9/5.
//  Copyright (c) 2015年 QXSX. All rights reserved.
//

#import "ShouYeLunBo.h"
#import "SMPageControl.h"
#import "DMLazyScrollView.h"
#import "PureLayout.h"
#import "UIView+LayoutConstraintHelper.h"
#import "UIImageView+AFNetworking.h"
#import "TMCache.h"
#import "QXNetWorkTool.h"
#import "APIAdress.h"
#import "LunboPicModel.h"
#import "UIViewController+NavItem.h"
#import "MBProgressHUD+YC.h"

@interface ShouYeLunBo ()<DMLazyScrollViewDelegate,QXNetWorkToolDelegate>
@property (nonatomic, strong) DMLazyScrollView *scrollView;
@property (nonatomic, strong) UIView *singleView;
@property (nonatomic, strong) NSMutableArray *specialTopics;
@property (nonatomic, strong) NSMutableArray *viewControllers4LazyScrollView;
@property (nonatomic, strong) SMPageControl * pageCtrler;
@property (nonatomic , strong) NSMutableArray *lunboPicArray;
@property (nonatomic , weak) IBOutlet UIImageView *loadingImage;
@property (assign , nonatomic) BOOL isDownLunBo;
@end

@implementation ShouYeLunBo

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    static BOOL isLaunch = YES;
    if (isLaunch && self.lunboPicArray != nil)
    {
        
        [self initUI];
        isLaunch = NO;
    }
    
    self.isDownLunBo = NO;
    
    //[self loadDatas];
    self.lunboPicArray = [[NSMutableArray alloc] init];
    
    // Do any additional setup after loading the view.
}

-(void)GetSuccessResponse:(id)Response andTag:(int)tag
{
    NSArray * picArr = Response;

    for(int i = 0 ; i < picArr.count; i ++)
    {
        id  luboPic = [picArr objectAtIndex:i];
        LunboPicModel *model = [LunboPicModel LuoPicWithDict:luboPic];
        [self.lunboPicArray addObject:model];
    }
    [self initUI];
    [self loadDatas];
    
    self.loadingImage.hidden = YES;
    
    self.isDownLunBo = YES;
}

-(void)GetFailResponse:(id)Response andTag:(int)tag
{
  //  [MBProgressHUD hideHUD];

}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (!self.isDownLunBo)
    {
        [self downShouYeLunBo];
    }
}

- (void)downShouYeLunBo
{
    QXNetWorkTool *QXnetWorkTool = [[QXNetWorkTool alloc]init];
    
    QXnetWorkTool.QXNetWorkDelegate = self;
    
    [QXnetWorkTool GetDataFromServerWithPostMethodandInterfaceName:ShouYeLunbboInterface andParameter:@[@{@"param":@"no"}] tag:1];
}

- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
   
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark -------------------- Loading ---------------------
- (void)loadDatas
{
    __weak __typeof(&*self)weakSelf = self;

    weakSelf.pageCtrler.numberOfPages = weakSelf.lunboPicArray.count;
    
    
    CGSize bestSize = [weakSelf.pageCtrler sizeForNumberOfPages:weakSelf.lunboPicArray.count];
    [weakSelf.pageCtrler.widthConstraint setConstant:bestSize.width];
    [weakSelf.pageCtrler.heightConstraint setConstant:bestSize.height];
    [weakSelf setViewControllers4LazyScrollViewWithAllNull];
    //weakSelf.scrollView.numberOfPages = weakSelf.specialTopics.count;
    weakSelf.scrollView.numberOfPages = weakSelf.lunboPicArray.count;
    
    [weakSelf.scrollView setEnableCircularScroll:YES];
    [weakSelf.scrollView setAutoPlay:YES];
   
    [weakSelf.scrollView reloadData];
    
    
//    [[APIClient sharedClient] GET:SpecialTopicUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        [weakSelf saveCachesDataWithRecords:responseObject];
//        [weakSelf.specialTopics removeAllObjects];
//        for (NSDictionary *dic in responseObject) {
//            TopicItem *item = [TopicItem creatItemWithParamters:dic];
//            [weakSelf.specialTopics addObject:item];
//        }
//        weakSelf.pageCtrler.numberOfPages = weakSelf.specialTopics.count;
//        CGSize bestSize = [weakSelf.pageCtrler sizeForNumberOfPages:weakSelf.specialTopics.count];
//        [weakSelf.pageCtrler.widthConstraint setConstant:bestSize.width];
//        [weakSelf.pageCtrler.heightConstraint setConstant:bestSize.height];
//        [weakSelf setViewControllers4LazyScrollViewWithAllNull];
//        weakSelf.scrollView.numberOfPages = weakSelf.specialTopics.count;
//        [weakSelf.scrollView setEnableCircularScroll:YES];
//        [weakSelf.scrollView setAutoPlay:YES];
//        if (weakSelf.specialTopics.count == 1) { //处理专题数为 1 的情况（DMLazyScrollView 在 numberOfPages 为 1 的时候无法正常显示）
//            
//            [weakSelf.scrollView setHidden:YES];
//            [weakSelf.singleView setHidden:NO];
//            UIButton *singleItemButton = [[UIButton alloc] initWithFrame:weakSelf.singleView.bounds];
//            UIImageView *singleImageView = [[UIImageView alloc] initWithFrame:weakSelf.singleView.bounds];
//            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?imageView2/2/w/%@", [[weakSelf.specialTopics firstObject] bannerOrigin], @(SCREEN_WIDTH * [[UIScreen mainScreen] scale])]];
//            [singleImageView sd_setImageWithURL:url placeholderImage:Poster_Placeholder_Landscape];
//            [weakSelf.singleView addSubview:singleImageView];
//            [singleItemButton addTarget:weakSelf action:@selector(onClickTopic:) forControlEvents:UIControlEventTouchUpInside];
//            [weakSelf.singleView addSubview:singleItemButton];
//            
//            [weakSelf.pageCtrler setHidesForSinglePage:YES];
//            [weakSelf.scrollView setEnableCircularScroll:NO];
//            [weakSelf.scrollView setAutoPlay:NO];
//        }
//        [weakSelf.scrollView reloadData];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        DLog(@"\nerror:%@",error.userInfo);
//    }];
    
}

#pragma mark -------------------- Properties ---------------------
- (NSMutableArray*)specialTopics
{
    if (!_specialTopics) {
        _specialTopics = [NSMutableArray array];
        [_specialTopics addObject:@"http://img6.cache.netease.com/house/2015/9/1/20150901093448e8d0d.jpg"];
        [_specialTopics addObject:@"http://p4.qhimg.com/dr/250_500_/t012f78266b2a3c2e71.jpg"];
        [_specialTopics addObject:@"http://img.pconline.com.cn/images/upload/upc/tx/ladyproduct/1501/09/c2/1679257_1420809599906_medium.jpg"];
        [_specialTopics addObject:@"http://www.hinews.cn/pic/0/16/85/86/16858610_749452.jpg"];
        [_specialTopics addObject:@"http://i2.cqnews.net/news/attachement/jpg/site82/20141128/d4bed9c8322515e2111a03.jpg"];
        
    }
    return _specialTopics;
}

- (NSMutableArray*)viewControllers4LazyScrollView
{
    if (!_viewControllers4LazyScrollView) {
        _viewControllers4LazyScrollView = [NSMutableArray array];
    }
    return _viewControllers4LazyScrollView;
}

- (void)setViewControllers4LazyScrollViewWithAllNull
{
    [self.viewControllers4LazyScrollView removeAllObjects];
    for (int i = 0; i < self.specialTopics.count; i++) {
        [self.viewControllers4LazyScrollView addObject:[NSNull null]];
    }
}

- (SMPageControl*)pageCtrler{
    if (!_pageCtrler) {
        _pageCtrler = [[SMPageControl alloc] initForAutoLayout];
        _pageCtrler.pageIndicatorImage = [UIImage imageNamed:@"ico_lunbo_white"];
        _pageCtrler.currentPageIndicatorImage = [UIImage imageNamed:@"ico_lunbo_green"];
        [self.view addSubview:_pageCtrler];
        [_pageCtrler autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:19];
        [_pageCtrler autoAlignAxisToSuperviewAxis:ALAxisVertical];
        [_pageCtrler autoSetDimensionsToSize:CGSizeMake(10, 10)];
        [_pageCtrler sizeToFit];
    }
    return _pageCtrler;
}

#pragma mark -------------------- UI init ---------------------
- (void)initUI
{
    
    self.view.backgroundColor = [UIColor blackColor];
    self.singleView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.scrollView = [[DMLazyScrollView alloc] initWithFrame:self.view.bounds];
    self.singleView.hidden = YES;
    self.scrollView.scrollsToTop = NO;
    __weak __typeof(&*self)weakSelf = self;
    self.scrollView.dataSource = ^(NSUInteger index) {
        return [weakSelf controllerAtIndex:index];
    };
    self.scrollView.numberOfPages = 0;
    self.scrollView.controlDelegate = self;
    [self.view addSubview:self.singleView];
    [self.view addSubview:self.scrollView];
    //[self setViewControllers4LazyScrollViewWithAllNull];
    [self showCachesData];
    
//    UIView *whiteLine = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-1, self.view.frame.size.width, 1)];
//    whiteLine.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:whiteLine];
    [self.view bringSubviewToFront:_pageCtrler];
}

- (void)showCachesData
{
//    NSArray *records = [[TMCache sharedCache] objectForKey:@"CachesObjectOfTopViewInFirstPage"];
//    if (records) {
//        for (NSDictionary *dic in records) {
//            TopicItem *item = [TopicItem creatItemWithParamters:dic];
//            [self.specialTopics addObject:item];
//        }
//        self.pageCtrler.numberOfPages = self.specialTopics.count;
//        if (self.pageCtrler.numberOfPages == 1) {
//            self.pageCtrler.hidesForSinglePage = YES;
//        }
//       
//    }
    CGSize bestSize = [self.pageCtrler sizeForNumberOfPages:self.lunboPicArray.count+1];
    [self.pageCtrler.widthConstraint setConstant:bestSize.width];
    [self.pageCtrler.heightConstraint setConstant:bestSize.height];
    [self setViewControllers4LazyScrollViewWithAllNull];
    self.scrollView.numberOfPages = self.lunboPicArray.count;
    
    [self.scrollView setEnableCircularScroll:YES];
    [self.scrollView setAutoPlay:YES];
    [self.scrollView reloadData];
}
#pragma mark -------------------- DMLazyScrollViewDelegate ---------------------
- (void)lazyScrollView:(DMLazyScrollView *)pagingView currentPageChanged:(NSInteger)currentPageIndex{
    self.pageCtrler.currentPage = currentPageIndex;
}
#pragma mark -------------------- For DMLazyScrollView ---------------------
- (UIViewController *) controllerAtIndex:(NSInteger) index {
//    if (index > self.specialTopics.count || index < 0) return nil;
//    id res = [self.viewControllers4LazyScrollView objectAtIndex:index];
//    if ([res isKindOfClass:[NSNull class]]) {
//        TopicItem *item = [self.specialTopics objectAtIndex:index];
//        UIViewController *contr = [[UIViewController alloc] init];
//        contr.view.frame = self.view.bounds;
//        UIImageView *subImageView = [[UIImageView alloc] initWithFrame:contr.view.bounds];
//        [contr.view addSubview:subImageView];
//        subImageView.contentMode = UIViewContentModeScaleAspectFill;
//        subImageView.clipsToBounds = YES;
//        
//        UIButton *topicActionButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        topicActionButton.frame = self.view.bounds;
//        [topicActionButton setTag:index];
//        [topicActionButton addTarget:self action:@selector(onClickTopic:) forControlEvents:UIControlEventTouchUpInside];
//        [contr.view addSubview:topicActionButton];
//        
//        __weak __typeof(&*subImageView)weakImgView = subImageView;
//        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?imageView2/2/w/%@", item.bannerOrigin, @(SCREEN_WIDTH * [[UIScreen mainScreen] scale])]];
//        
//        [subImageView setImageWithURLRequest:[NSURLRequest requestWithURL:url] placeholderImage:Poster_Placeholder_Landscape success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
//            weakImgView.image = image;
//        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
//            
//        }];
//        [self.viewControllers4LazyScrollView replaceObjectAtIndex:index withObject:contr];
//        return contr;
//    }
//    return res;
    if (index > self.specialTopics.count || index < 0) return nil;
    id res = [self.viewControllers4LazyScrollView objectAtIndex:index];
    if ([res isKindOfClass:[NSNull class]])
    {
        LunboPicModel * item = [self.lunboPicArray objectAtIndex:index];
        UIViewController *contr = [[UIViewController alloc] init];
        contr.view.frame = self.view.bounds;
        UIImageView *subImageView = [[UIImageView alloc] initWithFrame:contr.view.bounds];
        [contr.view addSubview:subImageView];
        subImageView.contentMode = UIViewContentModeScaleAspectFill;
        subImageView.clipsToBounds = YES;
        
        UIButton *topicActionButton = [UIButton buttonWithType:UIButtonTypeCustom];
        topicActionButton.frame = self.view.bounds;
        [topicActionButton setTag:index];
        [topicActionButton addTarget:self action:@selector(onClickPic:) forControlEvents:UIControlEventTouchUpInside];
        [contr.view addSubview:topicActionButton];
        
        __weak __typeof(&*subImageView)weakImgView = subImageView;

        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", item.img_url]];
        
        [subImageView setImageWithURLRequest:[NSURLRequest requestWithURL:url] placeholderImage:[UIImage imageNamed:@"img_shouye_loading"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
            
            weakImgView.image = image;
            
        } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
            
            weakImgView.image = [UIImage imageNamed:@"img_shouye_loading"];
            
        }];
        
        [self.viewControllers4LazyScrollView replaceObjectAtIndex:index withObject:contr];
        return contr;
    }
    return res;
}

-(void)onClickPic : (UIButton *)sender
{
    int tag = sender.tag;
    LunboPicModel * item = self.lunboPicArray[tag];
    NSURL *detailUrl = [NSURL URLWithString:item.img_display_url];
    UIViewController * vc = [[UIViewController alloc]init];
    UIWebView *webView = [[UIWebView alloc]initWithFrame:self.parentViewController.parentViewController.view.bounds];
    NSURLRequest *req = [NSURLRequest requestWithURL:detailUrl];
    [webView loadRequest:req];
//    [webView setScalesPageToFit:YES];
     [vc.view addSubview:webView];
    [self.parentViewController.parentViewController.navigationController pushViewController:vc animated:YES];
    [vc configNavigationBackAction:^{
        [vc.navigationController popViewControllerAnimated:YES];
    }];
}

@end
